<?php

function display_upload_plus($config){
	$config = ini_upload_config($config);
	$return = load_upload_script($config);
	$return .= 
		'<script type="text/javascript">
			$(function () {
			    "use strict";
			    $("#'.$config['id'].'").fileupload({
			        url: "'.$config['url'].'",
			        dataType: "json",
			        sequentialUploads: true,
			        formData: {"type": "'.$config['type'].'","rid": "'.$config['rid'].'"},
			        done: function (e, data) {
						if(data._response.result.status==1){
							if($("#'.$config['container']['id'].'").find("'.$config['container']['list_parent_tag'].'").length==0 ){
								$("#'.$config['container']['id'].'").append("<'.$config['container']['list_parent_tag'].'>");
							}
							$("#'.$config['container']['id'].'").find("'.$config['container']['list_parent_tag'].'")
								.append("<'.$config['container']['list_tag'].' id=\"file_"+data._response.result.fid+"\" node-type=\"file\"><img src="+data._response.result.tpath+" />"
								+"<input type=\"hidden\" name=\"fid[]\" value="+data._response.result.fid+" />"
								+"<a href=\"javascript:\" ctype=\"delete\" acturl=\"'.site_url('upload/delete/').'/"+data._response.result.fid+"\" rmelement=\"file_"+data._response.result.fid+"\"> 删除</a> <br />"
								+"<p>图片引用地址:<input type=\"text\" value="+data._response.result.path+" size=\"80\"  /></p>"
								+"</'.$config['container']['list_tag'].'>");
						}
						else {
							alert(data._response.result.error);
						}
			        },
			        progressall: function (e, data) {
			            var progress = parseInt(data.loaded / data.total * 100, 10);
 			            $("#progress .bar").css(
			                "width",
			                progress + "%"
			            );
			        }
			    }).prop("disabled", !$.support.fileInput)
			        .parent().addClass($.support.fileInput ? undefined : "disabled");
			});
		</script>';
	echo $return;
}

function ini_upload_config($config){
	if ( !isset($config['container']) ){
		$config['container'] = array(
				'id' => 'file_container',
				'list_parent_tag' => 'ul',
				'list_tag' => 'li'
		);
	}
	$config['type'] = isset($config['type']) ? $config['type'] : 'node';
	$config['rid']  = isset($config['rid']) ? $config['rid'] : 0;
	$config['url']  = isset($config['url']) ? $config['url'] :'/backend/upload/do_upload';
	return $config;
}

function load_upload_script(){
	$return = '';
	if ( !defined('UPLOAD_SCRIPT_LOAD') ){
		define('UPLOAD_SCRIPT_LOAD', true);
		$scripts = array(
				'theme/default/jqueryfileupload/js/vendor/jquery.ui.widget.js',
				'theme/default/jqueryfileupload/js/jquery.iframe-transport.js',
				'theme/default/jqueryfileupload/js/jquery.fileupload.js',
				);
		foreach ($scripts as $script){
			$return .=  '<script type="text/javascript" src="'.base_url(). $script.'"></script>';
		}
	}
	return $return;
}